package Region;
import java.io.*;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.nio.file.Files;

public class LogManager {
    Map<String, BufferedReader> readers;
    Map<String, BufferedWriter> writers;
    final static String filepath = "../logs";

    public LogManager() throws IOException {
        this.readers = new HashMap<>();
        this.writers = new HashMap<>();
        this.init();
    }

    public void init(){
        File directory = new File(filepath);
        // 检查目录是否存在，如果存在，则删除
        if (directory.exists()) {
            deleteDirectory(directory);
        }
        // 重新创建目录
        directory.mkdirs();
    }

    // 递归删除目录及目录中的所有内容
    private void deleteDirectory(File directory) {
        File[] allContents = directory.listFiles();
        if (allContents != null) {
            for (File file : allContents) {
                deleteDirectory(file);
            }
        }
        directory.delete();
    }

    public void createLog(String tableName) throws IOException {
        String filename = filepath+"/"+tableName+".txt";
        Path pathToFile = Paths.get(filename);

        if (Files.exists(pathToFile)) {
            System.out.println("文件已存在");
            return;
        }

        Files.createFile(pathToFile);

        BufferedReader tempReader = new BufferedReader(new FileReader(filename));
        BufferedWriter tempWriter = new BufferedWriter(new FileWriter(filename, true)); // 使用追加模式

        readers.put(tableName, tempReader);
        writers.put(tableName, tempWriter);

        System.out.println("新日志创建成功");
    }

    public void addLog(String tableName, String log) throws IOException {
        if(writers.get(tableName) == null){
            createLog(tableName);
        }
        BufferedWriter tempWriter = writers.get(tableName);
        tempWriter.append(log);
        tempWriter.newLine(); // 加上换行符
        tempWriter.flush(); // 确保写入到文件

        System.out.println("日志更新成功");
    }

    public void deleteLog(String tableName) {
        String filename = filepath+"/"+tableName+".txt";
        try {
            if (writers.containsKey(tableName)) {
                BufferedWriter oldWriter = writers.get(tableName);
                oldWriter.close();
                writers.remove(tableName);
            }
            if (readers.containsKey(tableName)) {
                BufferedReader oldReader = readers.get(tableName);
                oldReader.close();
                readers.remove(tableName);
            }
            new File(filename).delete(); // 删除文件本身
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("日志删除成功");
    }

    public ArrayList<String> readLog(String tableName) throws IOException {
        String filename = filepath+"/"+tableName+".txt";
        ArrayList<String> logs = new ArrayList<>();
        if (!readers.containsKey(tableName)) {
            throw new IOException("Log for " + tableName + " does not exist. Please create it first.");
        }
        // 暂时关闭和移除当前的reader，因为我们需要从头开始读取文件
        BufferedReader tempReader = readers.remove(tableName);
        tempReader.close();

        // 创建一个新的BufferedReader来从头读取文件
        tempReader = new BufferedReader(new FileReader(filename));
        readers.put(tableName, tempReader); // 替换掉旧的reader引用

        String line;
        while ((line = tempReader.readLine()) != null) {
            logs.add(line);
        }

        System.out.println("日志读出成功");
        return logs;
    }
}